<?php
/**
 * Created by PhpStorm.
 * User: hisheng
 * Date: 2017/6/6
 * Time: 17:55
 */
namespace App\Dao;
require_once(dirname(dirname(dirname(__FILE__))).'/alimns/mns-autoloader.php');
use AliyunMNS\Client;
use AliyunMNS\Topic;
use AliyunMNS\Constants;
use AliyunMNS\Model\MailAttributes;
use AliyunMNS\Model\SmsAttributes;
use AliyunMNS\Model\BatchSmsAttributes;
use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Exception\MnsException;
use AliyunMNS\Requests\PublishMessageRequest;

class AlimnsDao
{
    public function run($mobile,$code)
    {
        /**
         * Step 1. 初始化Client
         */
        $this->endPoint = "http://1900087871263204.mns.cn-hangzhou.aliyuncs.com/"; // eg. http://1900087871263204.mns.cn-shenzhen.aliyuncs.com
        $this->accessId = "LTAI0BBLz3zQG1Iu";//"LTAItgmqCg0B7zpq";//LTAI0BBLz3zQG1Iu
        $this->accessKey ="A6xPvfqp0G4gEjMiEYd571e37UBHp8";//"rN1aSnIpBpZhATxeJWWQJyzL2HZ3LX"//A6xPvfqp0G4gEjMiEYd571e37UBHp8;
        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);
       // var_dump($this->client);
        /**
         * Step 2. 获取主题引用
         */
        $topicName = "sms.topic-cn-hangzhou";//night-sms-topic
        $topic = $this->client->getTopicRef($topicName);
       // var_dump($topic);
        /**
         * Step 3. 生成SMS消息属性
         */
        // 3.1 设置发送短信的签名（SMSSignName）和模板（SMSTemplateCode）
        //$batchSmsAttributes = new BatchSmsAttributes("上海仁爱医院", "SMS_69195278");
        $batchSmsAttributes = new BatchSmsAttributes("张海生", "SMS_69900176");
       // var_dump($batchSmsAttributes);
        // 3.2 （如果在短信模板中定义了参数）指定短信模板中对应参数的值
        $batchSmsAttributes->addReceiver(strval($mobile), array("code" => strval($code)));//13816797387
        //var_dump($batchSmsAttributes);
        //$batchSmsAttributes->addReceiver("YourReceiverPhoneNumber2", array("YourSMSTemplateParamKey1" => "value1"));
        $messageAttributes = new MessageAttributes(array($batchSmsAttributes));
       // var_dump($messageAttributes);
        /**
         * Step 4. 设置SMS消息体（必须）
         *
         * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
         */
        $messageBody = "smsmessage";
        /**
         * Step 5. 发布SMS消息
         */
        $request = new PublishMessageRequest($messageBody, $messageAttributes);
       // var_dump($request);
        try
        {
            $res = $topic->publishMessage($request);
            //var_dump($res);
//            echo $res->isSucceed();
//            echo "\n";
//            echo $res->getMessageId();
//            echo "\n";
            return 1;
        }
        catch (MnsException $e)
        {
//            echo $e;
//            echo "\n";
            return 0;
        }
    }
}